import { defineConfig, loadEnv } from "vite";
import path from "path";
import createVitePlugins from "./vite/plugins";

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV } = env;
  return {
    // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上，你就需要用这个选项指定这个子路径。例如，如果你的应用被部署在 https://www.ruoyi.vip/admin/，则设置 baseUrl 为 /admin/。
    base: "/",
    plugins: [
      createVitePlugins(env, command === "build"),
    ],
    resolve: {
      alias: {
        // 设置别名
        "@": path.resolve(__dirname, "./src"),
        '@utils': path.resolve(__dirname, '../../packages/utils')
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    // vite 相关配置
    server: {
      port: 9091,
      host: true,
      open: false,
      cors: true,
      proxy: {
        "/tds-ec-api": {
          target: 'http://192.168.106.13:8090',//开发环境
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/tds-ec-api/, ""),
        }
      },
    },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
    // 打包增加哈希时间戳
    build: {
      rollupOptions: {
        output: {
          // 自定义输出文件名格式
          entryFileNames: `assets/[name]-[hash]-${new Date().getTime()}.js`,
          chunkFileNames: `assets/[name]-[hash]-${new Date().getTime()}.js`,
          assetFileNames: `assets/[name]-[hash]-${new Date().getTime()}.[ext]`
        }
      }
    },
    // qiankun 主应用配置
    define: {
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    },
    // 确保主应用可以正确加载子应用
    preview: {
      port: 9091,
      host: true,
      cors: true,
    }
  };
});
